<?php

require_once ('lib/OAuth.php');
include_once ('lib/facebook.php');

class FacebookApiHandler {

    // property declaration
    public $facebook;
    public $user;
    public $response;

    const app_id = '523682457680450';
    const secret = 'd6a793ffefb785f77f50461e5c4d01c7';

    public function __construct() {
        try {
        $facebook = new Facebook(array(
            'appId' => self::app_id,
            'secret' => self::secret,
        ));
        $user = $facebook->getUser();
        echo "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]" . "<br/>";
        if ($user) {
            $this->facebook = $facebook;
            $this->user = $user;          
            $params = array('next' => getLogoutURL());
            echo("$user is logged in.  Log out using <a href=" . $facebook->getLogoutUrl($params) . "> this link </a><br/>");
        } else {
            $params = array('next' => getIndexURL());
            echo("No user is currently logged in. Log in using <a href=" . $facebook->getLoginUrl($params) . "> this link </a><br/>");
        }
        echo "When trying to construct a user we got $user" . "<br/>";
        
        } catch (FacebookApiException $e) {
            echo $e->getTraceAsString();
        }
    }

    public function connect() {
        if (!$this->facebook) {
            die("You tried to use facebook without constructing an instance properly.");
        }
        if (!$this->user) {
            die("You need a user first before you can begin this miracle.");
        }
        $page_type = "RESTAURANT/CAFE";
        $my_friends = "SELECT uid2 FROM friend WHERE uid1 = $this->user";
        $liked_page_fans = "SELECT page_id FROM page_fan WHERE uid IN ($my_friends)";
        $page_query = "SELECT page_id, name, type, fan_count, categories FROM page WHERE page_id IN ($liked_page_fans) and type = '$page_type'";
        $response = $this->facebook->api(array(
            'method' => 'fql.query',
            'query' => $page_query,
        ));

        // Handle Yelp response data
        $this->response = $response;
    }

}
?>
